package demo1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:接口使用案例之Comparable
 * User: LianBao
 * Date: 2024-03-09
 * Time: 16:28
 */

class Student implements Comparable<Student> {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

/*    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }*/

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }

}

public class Test {

    public static void mySort(Comparable[] comparable) {
        for (int i = 0; i < comparable.length - 1; i++) {
            for (int j = 0; j < comparable.length - 1; j++) {
                if (comparable[j].compareTo(comparable[j + 1]) > 0) {
                    //交换
                    Comparable tmp = comparable[j];
                    comparable[j] = comparable[j + 1];
                    comparable[j + 1] = tmp;
                }
            }
        }
    }

    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("ZhangSan", 10);
        students[1] = new Student("lisi", 5);
        students[2] = new Student("WangWu", 15);
//        Arrays.sort(students);//报错
        mySort(students);
        System.out.println(Arrays.toString(students));

    }

    public static void main3(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("ZhangSan", 10);
        students[1] = new Student("lisi", 5);
        students[2] = new Student("WangWu", 15);
    }

    public static void main2(String[] args) {
        String str1 = "abcd";
        String str2 = "abcf";
        System.out.println(str1.compareTo(str2));
        //用于比两个较字符串的大小

    }

    public static void main1(String[] args) {
        Student student1 = new Student("zhangsan", 10);
        Student student2 = new Student("lisi", 5);

//        if (student1>student2) {}
        //引用数据类型不能通过大鱼号,小于号比较



        /* 使用Comparable接口可以解决这个问题!!
         * 只需要重写Comparable接口中的compareTo方法即可!!
         */
        int ret = student1.compareTo(student2);
//        compareTo返回值是int,如果student1>student2返回大于0的数,小于返回小于0的数,等于返回0

        if (ret > 0) {

        }

        /*
         * Comparable这个接口的缺陷:一旦写死了如何比较,后期就不能随意更改
         * */

    }
}
